package com.joysuch.wwyt.mh.storage.impl;

import com.joysuch.wwyt.mh.storage.IMonitorPointDataStorage;
import com.joysuch.wwyt.mh.storage.MonitorPointData;
import com.joysuch.wwyt.util.PageableUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.influxdb.InfluxDB;
import org.influxdb.dto.BatchPoints;
import org.influxdb.dto.Point;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * @author qingzhou
 * 2019-11-20
 */

@Slf4j
@Component
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class InfluxDBIMonitorPointDataStorage implements IMonitorPointDataStorage {

    private final InfluxDB influxDB;

    @Override
    public void store(@NotNull List<MonitorPointData> list) {
        long start = System.currentTimeMillis();
        log.info("******************* pointDataTest-dataSize:    " + list.size());
        if (list.size() == 0) {
            return;
        }
        if (list.size() > 100) {
            List<List<MonitorPointData>> lists = PageableUtil.groupByList(list, 100);
            for (List<MonitorPointData> dataList : lists) {
                saveData(dataList);
            }
        } else {
            saveData(list);
        }
        log.info("******************* pointDataTest-dataTime:  {}  ", (System.currentTimeMillis() - start));
    }

    private void saveData(List<MonitorPointData> list){
        BatchPoints batch = BatchPoints.database("major_hazard_monitor_point_data")
                .consistency(InfluxDB.ConsistencyLevel.ALL)
                .build();
        for (MonitorPointData data : list) {
            Point.Builder builder = Point.measurement(data.getTenentId() + "_" + data.getOrgCode())
                    .tag("tagId", data.getPointCode().toUpperCase())
                    .addField("value", data.getValue());
            batch.point(builder.build());
        }
        influxDB.write(batch);
    }
}
